package plus.H5D3B5016;

import android.app.Application;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;
import org.xutils.DbManager;
import org.xutils.x;

import java.io.File;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;

import plus.H5D3B5016.bean.Btc;
import plus.H5D3B5016.event.EventType;
import plus.H5D3B5016.event.MyEvent;
import plus.H5D3B5016.event.PriceEvent;
import plus.H5D3B5016.utils.ACache;
import plus.H5D3B5016.utils.BussinessWebSocketManager;
import plus.H5D3B5016.utils.FileSizeUtil;

public class App extends Application {



    public DbManager db;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void onCreate() {
        super.onCreate();
        try{
            x.Ext.init(this);
            initSocket();

            DbManager.DaoConfig daoConfig = new DbManager.DaoConfig()
                    .setDbName("macy_btc.db")
                    // 不设置dbDir时, 默认存储在app的私有目录.
                    //.setDbDir(dbFile) // "sdcard"的写法并非最佳实践, 这里为了简单, 先这样写了.
                    .setDbVersion(1)
                    .setDbOpenListener(new DbManager.DbOpenListener() {
                        @Override
                        public void onDbOpened(DbManager db) {
                            // 开启WAL, 对写入加速提升巨大
                            db.getDatabase().enableWriteAheadLogging();
                        }
                    })
                    .setDbUpgradeListener(new DbManager.DbUpgradeListener() {
                        @Override
                        public void onUpgrade(DbManager db, int oldVersion, int newVersion) {

                        }
                    });

            db = x.getDb(daoConfig);


            try{

                String dx=FileSizeUtil.getAutoFileOrFilesSize(db.getDatabase().getPath());
                Log.d("xxx","数据库大小:"+ dx);

                String s=dx.replaceAll("KB","").replaceAll("MB","GB");
                if(dx.indexOf("MB")>=0){
                    if(Double.valueOf(s)>=10){
                        db.delete(Btc.class);
                        Log.d("xxx","MB数据库已清理");
                    }
                }
                if(dx.indexOf("GB")>=0){
                    if(Double.valueOf(s)>=1){
                        db.delete(Btc.class);
                        Log.d("xxx","GB数据库已清理");
                    }
                }
            }catch (Exception ee){}
        }catch (Exception e){}




    }

    private void initSocket(){
        BussinessWebSocketManager.getInstance()
                .init(Const.SOCKET_URL)
                .setOnBussinessWebSocketListener(new BussinessWebSocketManager.OnBussinessWebSockeListener() {
                    @Override
                    public void onTestMessage(String text) {
                        try {
                            JSONObject my=new JSONObject(text);
                            if(my.has("candlestick")){
                                JSONObject jo=my.getJSONObject("candlestick");
                                if(jo.has("symbol")&&jo.getString("symbol").equals("btcusdt")){
                                    save(new MyEvent(EventType.READ,jo));
                                    EventBus.getDefault().postSticky(new MyEvent(EventType.READ,jo));
                                }
                            }else if(my.has("priceDepth")){
                                JSONObject jo=my.getJSONObject("priceDepth");
                                if(jo.has("symbol")&&jo.getString("symbol").equals("btcusdt")){
                                    EventBus.getDefault().postSticky(new MyEvent(EventType.MRMC,jo));
                                }
                            }else if(my.has("lastTrade")){
                                //JSONObject jo=my.getJSONObject("lastTrade");
                            }else{
                                Log.d("xxx","特别类型:"+text);
                            }

                            JSONObject jo=my.getJSONObject("candlestick");
                            if(jo.has("symbol")&&jo.getString("symbol").equals("btcusdt")){
                                //Log.d("xxx",text);
                                EventBus.getDefault().postSticky(new MyEvent(EventType.READ,jo));
                            }
                        }catch (Exception e){}
                    }
                });
    }

    public String getSDPath(){
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(Environment.MEDIA_MOUNTED);//判断sd卡是否存在
        if(sdCardExist)
        {
            sdDir = Environment.getExternalStorageDirectory();//获取跟目录
        }
        return sdDir.toString();
    }


    /**
     * 保存数据
     * @param myEvent
     */
    public  void save(MyEvent myEvent){
        try {
            if(myEvent.getType()!= EventType.READ){
                return;
            }
            JSONObject jo=(JSONObject)myEvent.getObj();
            double close=jo.getDouble("close");// 最新价
            double max=jo.getDouble("high");// 最大
            double min=jo.getDouble("low");// 最小
            Long timestamp=jo.getLong("timestamp");// timestamp

            db.save(new Btc(close,max,min,sdf.format(new Date(timestamp))));

            click(close,new Date(timestamp));

        }catch (Exception e){}
    }


    /**
     * 检测 涨幅
     */
    private void click(double myclose,Date mydate){
        try {
            String txst=ACache.get(getApplicationContext()).getAsString("txst");
            String txet=ACache.get(getApplicationContext()).getAsString("txet");
            int st=30;
            int et=30;
            if(null!=txst){
                st=Integer.valueOf(txst);
            }
            if(null!=txet){
                et=Integer.valueOf(txet);
            }

            Calendar c = new GregorianCalendar();
            c.setTime(mydate);
            c.add(Calendar.SECOND,-st);
            java.util.Date beforeDate=c.getTime();

            Btc btc=db.selector(Btc.class).where("timestamp",">=",sdf.format(beforeDate)).orderBy("close",true).findFirst();
            if(null==btc||myclose<=0){
                return;
            }


            double zf=myclose-btc.getClose();


            if(Math.abs(zf)>et){
                defaultMediaPlayer(st);
            }

//            String d="数据库大小:"+ FileSizeUtil.getAutoFileOrFilesSize(db.getDatabase().getPath());
//            Log.d("xxx",d);

            EventBus.getDefault().postSticky(new PriceEvent(zf));

        }catch (Exception e){
            Log.e("xxx",e.getMessage());
        }
    }


    private long exitTime = 0;
    public void defaultMediaPlayer(int miao) {
        try {
            if ((System.currentTimeMillis() - exitTime) < (miao*1000)) {
                return;
            }
            exitTime = System.currentTimeMillis();
            Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            Ringtone r = RingtoneManager.getRingtone(this, notification);
            r.play();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * top 5
     * {"priceDepth":{"data":{"asks":[{"amount":9.2356,"price":212.28},{"amount":0.1327,"price":212.29},{"amount":50,"price":212.3},{"amount":2.356,"price":212.31},{"amount":7.959,"price":212.33}],"bids":[{"amount":485.3259,"price":212.27},{"amount":0.4151,"price":212.24},{"amount":54.4924,"price":212.23},{"amount":1.4195,"price":212.22},{"amount":1.5,"price":212.21}],"timestamp":1588908178745},"symbol":"ethusdt","symbolName":"ETH/USDT","timestamp":1588908178749}}
     */
}
